package com.huawei.esdk.uc.device.common;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.huawei.ecs.bin.common.Connection;
import com.huawei.ecs.bin.common.ConnectionMgr;
import com.huawei.ecs.mtk.log.SimpleLogger;
import com.huawei.esdk.platform.common.bean.config.DeviceConfig;
import com.huawei.esdk.platform.common.config.ConfigManager;
import com.huawei.esdk.platform.common.utils.ApplicationContextUtil;
import com.huawei.esdk.platform.nemgr.itf.IDeviceManager;
import com.huawei.esdk.uc.device.AbstractU19Capability;
import com.huawei.esdk.uc.device.base.U19DeviceConnectionBase;

/**
 * U19连接管理类
 * 启动时初始化U19设备连接，用于缓存连接
 * <p>
 * @author  c00316442
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class U19DeviceManager
{
    private static final Logger LOGGER = Logger.getLogger(U19DeviceManager.class);
    
    public void init()
    {
        boolean isSSL = false;
        String connectionProtocol = ConfigManager.getInstance().getValue("u19.connection.protocol");
        if ("TLS".equalsIgnoreCase(connectionProtocol))
        {
            isSSL = true;
        }
        
        LOGGER.info("eSDK connect to U19 protocol : " + connectionProtocol);
        
        // 获取U19设备列表，U19V1R1C20
        IDeviceManager deviceManager = ApplicationContextUtil.getBean("deviceManager");
        List<DeviceConfig> deviceConfigs = deviceManager.queryDeviceInfosByType("U19V1R1C20");
        
        if (null == deviceConfigs || deviceConfigs.isEmpty())
        {
            U19DeviceConnectionBase.setDeviceConnectionMap(null);
            LOGGER.warn("U19 devices config is null.");
            return;
        }
        else
        {
            LOGGER.info("Init U19 connection start.");
            
            initU19Logger();
            
            Map<String, Object> deviceConnectionMap = new HashMap<String, Object>();
            
            for (DeviceConfig deviceConfig : deviceConfigs)
            {
                Connection connection = AbstractU19Capability.initConn(deviceConfig, isSSL);
                
                if (null != connection)
                {
                    try
                    {
                        URL serverUrl = new URL(deviceConfig.getServiceAccessPoint());
                        String serverIp = serverUrl.getHost();
                        deviceConnectionMap.put(serverIp, connection);
                    }
                    catch (MalformedURLException e)
                    {
                        continue;
                    }
                }
            }
            
            U19DeviceConnectionBase.setDeviceConnectionMap(deviceConnectionMap);
            LOGGER.info("Init U19 connection finish, successful connection size : " + deviceConnectionMap.size());
        }
    }
    
    public void initU19Logger()
    {
        // 获取U19 BinSocket日志级别
        String logLevel = ConfigManager.getInstance().getValue("log4j.logger.u19.log.level");
        
        // 打印到eSDK-Server.run.log中
        String serverLogPath = ConfigManager.getInstance().getValue("log4j.appender.fileLogger.File");
        String catalinaBase = System.getProperty("catalina.base");
        serverLogPath = catalinaBase + serverLogPath.substring(16);
        
        com.huawei.ecs.mtk.log.Logger.setLogger(new SimpleLogger(serverLogPath));
        com.huawei.ecs.mtk.log.Logger.setup("(default(" + logLevel + ")TCP(" + logLevel + "))");
        com.huawei.ecs.mtk.log.Logger.open();
    }
    
    public void destroy()
    {
        List<Object> list = U19DeviceConnectionBase.getConnMgrList();
        
        if (null != list && !list.isEmpty())
        {
            for (Object o : list)
            {
                ConnectionMgr mgr = (ConnectionMgr)o;
                mgr.shutdown();
            }
        }
        
        com.huawei.ecs.mtk.log.Logger.close();
    }
}
